package handles

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"time"
	"video-hub/cache"
	"video-hub/models"
)

func VideoList(c *gin.Context) {
	var video []models.Video
	redis_key := "list"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Find(&video)
		jsonData, _ := json.Marshal(video)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &video)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "成功",
		"data": video,
	})
	return
}

func VideoDetail(c *gin.Context) {
	id := c.Query("id")
	var video models.Video
	redis_key := "detail_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Where("id=?", id).Find(&video)
		jsonData, _ := json.Marshal(video)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &video)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "成功",
		"data": video,
	})
	return
}

func Add(c *gin.Context) {
	title := c.PostForm("title")
	comment := c.PostForm("comment")

	if title == "" || comment == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "点赞失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "点赞成功",
	})
	return
}
